package com.googlecode.grima.servlet;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.googlecode.grima.domain.DescriptiveItem;
import com.googlecode.grima.service.DescriptiveItemService;
import com.googlecode.grima.util.IOUtil;

public class DescriptiveImageServlet extends HttpServlet {

	/**
	 * 
	 */
  private static final long serialVersionUID = -7440351597533437546L;
	
  private DescriptiveItemService descriptiveItemService;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
	  super.init(config);
	  
	  WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
	  this.descriptiveItemService = (DescriptiveItemService) springContext.getBean("descriptiveItemService");
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String id = request.getParameter("id");
		String reference = request.getParameter("reference");
		
		if ( (id == null) && (id == null)) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
			return;
		}

		InputStream is = getImage(Long.valueOf(id), reference);
		if (is == null) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
			return;
		}

		OutputStream os;
		try {
			os = response.getOutputStream();
			IOUtil.copyStream(is, os);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public InputStream getImage(Long id, String reference) {

		InputStream ret = null;

		List<DescriptiveItem> items = descriptiveItemService.findByParameters(id, reference);
		if ((items != null) && (items.size() > 0)){
			DescriptiveItem descriptiveItem = items.get(0);
			byte[] imagem = descriptiveItem.getImagem();
			if (imagem != null) {
				ret = new ByteArrayInputStream(imagem); 
			}

		}
		return ret;
	}

}